const path = require("path");

const Koa = require("koa");
/* const { createProxyMiddleware } = require("http-proxy-middleware");
const koaConnect = require("koa2-connect"); */
//?const proxy = require("koa-server-http-proxy");
/* const proxy = require("koa2-nginx"); */
const koaBody = require("koa-body");
const KoaStatic = require("koa-static");

const router = require("../router");
const errHandler = require("./errHandler");

const app = new Koa();

//* 代理配置 start */

/* app.use(proxy({ "/": { target: "http://coralmh.xyz", changeOrigin: true } })); */

/* app.use(
  proxy("/", {
    target: "http://coralmh.xyz",
    pathRewrite: { "^/": "/" },
    changeOrigin: true,
  })
); */

/* const proxy = require("koa2-proxy-middleware"); //?引入代理模块
const options = {
  targets: {
    //todo  (.*) means anything
    "/(.*)": {
      target: "http://coralmh.xyz",
      changeOrigin: true,
    },
  },
};
app.use(proxy(options)); */

/* app.use(
  koaConnect(
    // ?代理全部以 / 开头的 HTTP 请求
    createProxyMiddleware("/", {
      target: "http://coralmh.xyz", //? 目标服务器地址
      changeOrigin: true, //? 允许跨域
    })
  )
);
 */

app.use(
  koaBody({
    multipart: true,
    formidable: {
      //* 在配置选项 option 里, 不推荐使用相对路径
      //* 在option里的相对路径, 不是相对的当前文件, 相对process.cwd()
      //?  uploadDir: "./src/upload", */
      uploadDir: path.join(__dirname, "../upload"),
      keepExtensions: true,
    },
  })
);
app.use(KoaStatic(path.join(__dirname, "../upload")));
app.use(router.routes()).use(router.allowedMethods());

//! 统一的错误处理
app.on("error", errHandler);

module.exports = app;
